<template>
  <div>
    <h1>办理开卡</h1>
    <div class="ring_bg">
      <div v-show="currentCard.id" style="width: 700px;margin: 30px auto">
        <div style="font-size: 30px;font-weight: bolder;margin: 10px 0 10px 70px ">
            <span v-if="currentCard.operator==='03'" class="iconfont icon-yidong"  style="color: #7eb95e;font-size:30px;margin-right: 20px"></span>
            <span v-if="currentCard.operator==='02'" class="iconfont icon-liantong" style="color: #d62119;font-size:30px;margin-right: 20px"></span>
            <span v-if="currentCard.operator==='01'" class="iconfont icon-dianxin" style="color: #489af6;font-size:30px;margin-right: 20px"></span>
          {{ currentCard.cardNo }}<br>
          <el-tag style="line-height: 24px;height: 24px;margin-left:50px ">
            {{ currentCard.aaaaNoTypeName ? `靓号类型：${currentCard.aaaaPackageName}` : `低消套餐：${currentCard.packageName}` }}
          </el-tag>
          <el-tag style="line-height: 24px;height: 24px" v-if="currentCard.aaaaNoTypeName">靓号类型：{{
              currentCard.aaaaNoTypeName
            }}
          </el-tag>
          <el-tag style="line-height: 24px;height: 24px">最低预存：{{
              currentCard.minPreStorm
            }}
          </el-tag>
          <el-tag style="line-height: 24px;height: 24px">合约期：{{
              currentCard.contractPeriod
            }}
          </el-tag>
          <el-tag style="line-height: 24px;height: 24px">开卡费：{{
              currentCard.cardOpeningFee
            }}
          </el-tag>
        </div>

        <el-divider></el-divider>
        <div class="template-form">
          <el-form :model="currentCard" ref="currentCard" label-width="100px" :rules="rules"
                   class="template-form__list">
            <el-row :gutter="10">
              <el-col :span="12" style="width: 100%">
                <el-form-item label="请选择套餐：" prop="telecomPackageId">
                  <el-select v-model="currentCard.telecomPackageId" placeholder="请选择套餐" style="width: 100%">
                    <el-option v-for="{id,packageName} in effectivePackageList" :label="packageName" :value="id"
                               :key="id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="22">
                <el-form-item label="上传身份证照片：" prop="idCardZmPath" style="position: relative">
                  <el-upload :action="uploadUrl" list-type="picture-card" ref="upload1" :auto-upload="true" :on-preview="handlePictureCardPreview"
                             :limit="1" :on-remove="deleteFile1" :file-list="idCardZmList" accept=".jpeg,.jpg,.png"
                             :on-success="upload1Success" :headers="{'token':localStorage.getItem('token')}"
                             style="display: inline-block;margin-right: 20px;vertical-align: middle;">
                    <i slot="default" class="el-icon-plus"></i>
                  </el-upload>
                  <el-upload :action="uploadUrl" list-type="picture-card" ref="upload2" :auto-upload="true" :on-preview="handlePictureCardPreview"
                             :limit="1" :on-remove="deleteFile2" :file-list="idCardFmList" accept=".jpeg,.jpg,.png"
                             :headers="{'token':localStorage.getItem('token')}"
                             :on-success="upload2Success" style="display: inline-block;vertical-align: middle;">
                    <i slot="default" class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
              </el-col>
              <el-col :span="22" style="margin-top: -10px">
                <el-form-item>
                  <div><i class="el-icon-info"></i>上传图片格式为：jpg、jpeg、png</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="用户姓名：" prop="userName">
<!--                  :readonly="readonly"-->
                  <el-input v-model="currentCard.userName" :readonly="readonly" placeholder="请使用读卡器读取用户姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号：" prop="idCardNo">
                  <el-input v-model="currentCard.idCardNo" :readonly="readonly" placeholder="请使用读卡器读取身份证号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="22">
                <el-form-item label="上传半身照片：" prop="halfPhotoPath" style="position: relative">
                  <el-upload :action="uploadUrl" list-type="picture-card" ref="upload3" :auto-upload="true" :on-preview="handlePictureCardPreview"
                             :limit="1" :on-remove="deleteHalfPhotoPath" :file-list="halfPhotoPathList" accept=".jpeg,.jpg,.png"
                             :on-success="uploadHalfPhotoSuccess" :headers="{'token':localStorage.getItem('token')}">
                    <i slot="default" class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="22" style="margin-top: -10px">
                <el-form-item>
                  <div><i class="el-icon-info"></i>上传图片格式为：jpg、jpeg、png</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="type==='1'">
              <el-col :span="12">
                <el-form-item label="区域：" prop="areaId">
                  <el-select v-model="currentCard.areaId" placeholder="请选择区域">
                    <el-option v-for="{id,name} in areaCodeList" :label="name" :value="id"
                               :key="id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-if="type==='1'">
              <el-col :span="12">
                <el-form-item label="详细地址：" prop="address">
                  <el-input v-model="currentCard.address" placeholder="请输入详细地址"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12" style="width: 100%">
                <el-form-item label="备注：" prop="remarks">
                  <el-input v-model="currentCard.remarks" placeholder="请输入备注" type="textarea" rows="5" resize="none"
                            maxlength="200" show-word-limit style="width: 100%"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

        </div>
      </div>

    </div>
    <div class="dialog-footer">
      <span slot="footer">
            <el-button @click="cancel" type="danger">取消</el-button>
            <el-button type="primary" :loading="loading" @click="saveOrder">保存</el-button>
          </span>
    </div>
  </div>
</template>

<script>
import request from "@/utils/Request";
import {mapMutations} from 'vuex'
import {httpReadInfo, hex2a, conWS} from "@/utils/IdCardUtil";
import EventBus from '@/utils/EventBus'
import {getImgBlob} from "@/utils/Common";

export default {
  name: "CardOpen",
  data() {
    const validateIdCard = (rule, value, callback) => {
      if (!!!this.currentCard.idCardZmPath || !!!this.currentCard.idCardFmPath) {
        callback(new Error('请上传身份证'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      localStorage: localStorage,
      readonly: false,
      idCardZmList: [],
      idCardFmList: [],
      halfPhotoPathList: [],
      currentCard: {},
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: window.config.BASE_API + '/upload/img',
      effectivePackageList: [],
      areaCodeList: [],
      type: '1',
      action: 'add',
      rules: {
        idCardZmPath: [
          {
            required: true, validator: (rule, value, callback) => {
              validateIdCard.bind(this);
              return validateIdCard(rule, value, callback);
            }, trigger: 'change'
          }
        ],
        userName: [
          {required: true, message: '请使用读卡器读取用户姓名', trigger: 'change'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        idCardNo: [
          {required: true, message: '请使用读卡器读取身份证号', trigger: 'change'},
          {min: 15, max: 18, message: '长度在 15 到 18 个字符', trigger: 'blur'}
        ],
        halfPhotoPath: [
          {required: true, message: '请上传半身照', trigger: 'change'},
        ],
        areaId: [
          {required: true, message: '请请选择区域', trigger: 'change'},
        ],
        address: [
          {required: true, message: '请输入家庭住址', trigger: 'blur'},
          {min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur'}
        ],
        phoneNo: [
          {required: true, message: '请输入电话', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur'}
        ],
        loginId: [
          {required: true, message: '请输入登录账号', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.initAreaCode();
      this.type = this.$route.query.type;
      const orderId = this.$route.query.orderId;
      if (!!orderId) {//订单驳回后编辑
        this.action = 'edit';//标记编辑  保存的时候提交后台
        request.get("/openCardOrder/entity", {params: {orderId}}).then(({data}) => {
          if (data.success) {
            const {noCard, openCardOrder, telecomPackageId} = data.data;
            this.currentCard = {...JSON.parse(JSON.stringify(noCard)), ...openCardOrder, telecomPackageId, 'oriCardId': noCard.id};
            getImgBlob(this.currentCard.idCardZmPath, this.currentCard.idCardZmName).then(url => {
              this.idCardZmList = [{name: this.currentCard.idCardZmName, url}];
            });
            getImgBlob(this.currentCard.idCardFmPath, this.currentCard.idCardFmName).then(url => {
              this.idCardFmList = [{name: this.currentCard.idCardFmName, url}];
            });
            getImgBlob(this.currentCard.halfPhotoPath, this.currentCard.halfPhotoName).then(url => {
              this.halfPhotoPathList = [{name: this.currentCard.halfPhotoName, url}];
            });
            this.initEffectivePackageList();
            this.initHttpId();
          } else {
            this.$message({type: 'error', message: data.message});
          }
        }).catch(err => {
          this.$message({type: 'error', message: "失败"});
          console.log(err)
          return false;
        });
      } else {//新开卡或新融合
        this.action = 'add';
        request.get("/noCard/getInfo", {params: {id: this.$route.query.id}}).then(({data}) => {
          if (data.success) {
            this.currentCard = {
              ...data.data,
              idCardZmPath: null,
              idCardFmPath: null,
              halfPhotoPath: null, userName: '', idCardNo: ''
            };
            this.idCardZmList = [];
            this.idCardFmList = [];
            this.halfPhotoPathList = [];
            this.initEffectivePackageList();
            this.initHttpId();
          } else {
            this.$message({type: 'error', message: data.message});
          }
        }).catch(err => {
          this.$message({type: 'error', message: "失败"});
          console.log(err)
        })
      }
    },
    initHttpId() {
      httpReadInfo().then(({success, _userName, _idCardNo,_photo, error}) => {
        if (success) {
          this.currentCard.idCardNo = hex2a(window.atob(_idCardNo)).trim();
          this.currentCard.userName = hex2a(window.atob(_userName)).trim();
          this.currentCard.idCardPhoto = _photo;
        } else {
          this.initWs();
          console.error(error)
        }
      }).catch(e => {
        console.error(e)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    initWs() {
      const ws = conWS();
      ws.onopen = (evt) => {
        this.$message({type: 'success', message: '读卡程序已就绪'});
      };
      ws.onmessage = this.onWsMessage
    },
    onWsMessage(messageEvent) {
      const jsonObject = JSON.parse(messageEvent.data);
      if (jsonObject.Ret === 0) {
        if (jsonObject.Cmd === 10001) {
          const szParam = JSON.parse(window.atob(jsonObject.UserParam));
          this.currentCard.userName = hex2a(window.atob(szParam.CardInfo.Name)).trim();
          this.currentCard.idCardNo = hex2a(window.atob(szParam.CardInfo.No)).trim();
          this.currentCard.idCardPhoto = 'data:image/jpg;base64,' + szParam.BmpInfo;
        }
      } else {
        this.this.$message({type: 'error', message: '读取信息失败，请确认读卡器正确安装'});
      }
    },
    cancel() {
      this.$router.history.go(-1);
      this.removeTab('/CardOpen')
    },
    initAreaCode() {
      request.get('/common/getAreaCode').then(({data}) => {
        if (data.success) {
          this.areaCodeList = data.data;
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询区域码表失败"});
        console.log(err)
      })
    },
    initEffectivePackageList() {
      request.get('/telecomPackage/getEffectiveList', {
        params: {
          operator: this.currentCard.operator,
          packagePrice: this.currentCard.packagePrice
        }
      }).then(({data}) => {
        if (data.success) {
          this.effectivePackageList = data.data;
        }
      }).catch(err => {
        this.$message({type: 'error', message: "查询套餐列表失败"});
        console.log(err)
      })
    },
    async saveOrder() {
      const validate = await new Promise((resolve, reject) => {
        this.$refs.currentCard.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            resolve(false);
          }
        });
      })
      if (!validate) {
        return;
      }
      const confirm = await this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return true;
      }).catch(() => {
        return false;
      });
      if (!confirm) {
        return;
      }
      this.loading = true;
      request.post('/openCardOrder/save', {...this.currentCard, businessType: this.type, action: this.action}).then(({data}) => {
        if (data.success) {
          this.$message({type: 'success', message: "办理成功，请等待审批"});
          EventBus.$emit('saveOrderSuccess');
          this.$router.history.go(-1);
          this.removeTab('/CardOpen')
        } else {
          this.$message({type: 'warning', message: data.message});
        }
      }).catch(err => {
        this.$message({type: 'error', message: "办理失败，请联系管理员"});
        console.log(err)
      }).finally(() => {
        this.loading = false;
      });
    },
    upload1Success({success, data}, file, fileList) {
      if (!success) {
        this.$message({type: 'error', message: "上传身份证失败"});
      } else {
        this.currentCard.idCardZmName = data.originalFilename;
        this.currentCard.idCardZmPath = data.filePath;
        this.idCardZmList = fileList;
      }
    },
    uploadHalfPhotoSuccess({success, data}, file, fileList) {
      if (!success) {
        this.$message({type: 'error', message: "上传身份证失败"});
      } else {
        this.currentCard.halfPhotoName = data.originalFilename;
        this.currentCard.halfPhotoPath = data.filePath;
        this.halfPhotoPathList = fileList;
      }
    },
    upload2Success({success, data}, file, fileList) {
      if (!success) {
        this.$message({type: 'error', message: "上传身份证失败"});
      } else {
        this.currentCard.idCardFmName = data.originalFilename;
        this.currentCard.idCardFmPath = data.filePath;
        this.idCardFmList = fileList;
      }
    },
    deleteFile1() {
      this.idCardZmList = [];
      this.currentCard.idCardZmName = null;
      this.currentCard.idCardZmPath = null;
    },
    deleteFile2() {
      this.idCardFmList = [];
      this.currentCard.idCardFmName = null;
      this.currentCard.idCardFmPath = null;
    },
    deleteHalfPhotoPath() {
      this.halfPhotoPathList = [];
      this.currentCard.halfPhotoName = null;
      this.currentCard.halfPhotoPath = null;
    },
    ...mapMutations(['removeTab'])
  },
  watch: {
    idCardZmList(val) {
      if (val.length === 1) {
        this.$refs.upload1.$children[1].$el.style.display = "none";
      } else {
        this.$refs.upload1.$children[1].$el.style.display = ''
      }
    },
    idCardFmList(val) {
      if (val.length === 1) {
        this.$refs.upload2.$children[1].$el.style.display = "none";
      } else {
        this.$refs.upload2.$children[1].$el.style.display = ''
      }
    },
    halfPhotoPathList(val) {
      if (val.length === 1) {
        this.$refs.upload3.$children[1].$el.style.display = "none";
      } else {
        this.$refs.upload3.$children[1].$el.style.display = ''
      }
    }
  },
}
</script>

<style scoped>

.ring_bg {
  padding: 20px;
  background: #fff;
  border-radius: 3px;
  border: 1px solid #EBEEF3;
  margin: 20px auto;
  min-height: 600px;
  margin-bottom: 70px;
}

.template-form__list {
  margin: 20px auto;
}

.dialog-footer {
  background: #fff;
  box-shadow: 4px 4px 15px rgba(0, 0, 0, 0.2);
  width: -moz-calc(100% - 240px);
  width: -webkit-calc(100% - 240px);
  position: fixed;
  width: calc(100% - 240px);
  right: 0;
  bottom: 0;
  height: 70px;
  align-items: center;
  display: flex;
  justify-content: center;

}

.ring_delete {
  background: rgba(0, 0, 0, 0.6);
  width: 150px;
  height: 150px;
  align-items: center;
  position: absolute;
  top: 0;
  display: flex;
  justify-content: center;
  vertical-align: middle;
}

.ring_after {
  position: relative;
  display: inline-block;
}

.ring_after img {
  width: 150px;
  height: 150px;
  vertical-align: middle;
}
</style>